var DeviceModule = function () {
    var editable = function () {

        return {
            init: function () {
            	//表格初始化
                var oTable = $('#deviceEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":true,
                    "scrollX":true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "zeroRecords":"数据为空",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>---<center>",
						    "targets": [7]
						}            
                    ],
                    "columns": [
                       { "data": "iSerialNumber" ,'sortable': false,"defaultContent": "" },
                       { "data": "pSerialNumber" ,'sortable': false,"defaultContent": "" },
                       { "data": "sim" ,'sortable': false,"defaultContent": "" },
                       { "data": "endTime" ,'sortable': false,"defaultContent": "" },
                       { "data": "employeeName" ,'sortable': false,"defaultContent": "<center>---<center>" },
                       { "data": "allocatedTime" ,'sortable': false,"defaultContent": "<center>---<center>" },
                       { "data": "allocated" ,'sortable': false,"defaultContent": "" },
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/device/query",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   nRow.children[1].id = aData.orgId;
                	   var allocated = "";
                	   var operation = ""
                	   
                	   if(aData.employeeName == undefined){
                		   $('td:eq(4)', nRow).html("");
                	   }
                	   if(0 == aData.allocated && 1 == aData.state){
                		   allocated = "未分配";
                		   operation = 
                			   '<a title="分配" class="distribution fa fa-user fa-lg pull-left" href="javascript:;"></a>\
                			   &nbsp;<a class="repair fa fa-wrench fa-lg pull-left" title="报修" href="javascript:;"></a>';
                	   }else if(0 == aData.allocated && 2 == aData.state){
                		   allocated = "报修中";
                		   operation = '';
                	   }else if(0 == aData.allocated && 3 == aData.state){
                		   allocated = "修理中";
                		   operation = '';
                	   }else if(1 == aData.allocated && 1 == aData.state){
                		   allocated = "已分配";
                		   operation = 
                			   '<a class="pullback fa fa-unlink fa-lg pull-left" title="回收设备" href="javascript:;"></a>\
                			   &nbsp;<a class="repair fa fa-wrench fa-lg pull-left" title="报修" href="javascript:;"></a>';
                	   }else if(1 == aData.allocated && (2 == aData.state||3 == aData.state)){
                		   allocated = "已分配";
                		   operation = 
                			   '<a class="pullback fa fa-unlink fa-lg pull-left" title="回收设备" href="javascript:;"></a>';
                	   }
                	   $('td:eq(3)', nRow).html(timestampToDate(aData.endTime,false));
                	   if(aData.employeeName == undefined||aData.employeeName == ""){
                		   $('td:eq(4)', nRow).html("<center>--<center>");
                	   }else{
                		   $('td:eq(4)', nRow).html(aData.employeeName + "(工号:" + aData.employeeNo + ")");
                	   }
                	   $('td:eq(5)', nRow).html(timestampToDate(aData.allocatedTime,false));
                	   $('td:eq(6)', nRow).html(allocated);
                	   $('td:eq(7)', nRow).html(operation);
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   var orgId = $("#org_id").attr("value");
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json +',"orgId":"'+orgId+ '"}';
                       $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                
                //function
                //时间戳转换为日期字符串
                function timestampToDate(timestamp, isFull){
                	if(undefined == timestamp){
                		return "<center>--</center>"
                	}
                	var date = Date.parse(timestamp);
                	var time = new Date();
                	//火狐对new date()直接传入字符串的不支持
                	if(isNaN(date)){
                		var arr = timestamp.split(' ')[0].split('-');
                		time = new Date(arr[0],arr[1],arr[2]);
                	}else{
                		time = new Date(timestamp);
                	}
                    var ymdhis = "";
                    ymdhis += time.getFullYear() + "-";
                    if(time.getMonth()+1 < 10){
                    	ymdhis += "0" + (time.getMonth()+1) + "-";
                    }else{
                    	ymdhis += (time.getMonth()+1) + "-";
                    }
                    if(time.getDate() < 10){
                    	ymdhis += "0" + time.getDate();
                    }else{
                    	ymdhis += time.getDate();
                    }
                    
                    if (isFull === true)
                    {
                        ymdhis += " " + time.getHours() + ":";
                        ymdhis += time.getMinutes() + ":";
                        ymdhis += time.getSeconds();
                    }
                    return ymdhis;
                }
                
                // 详情
                /*$('#deviceEditable').on("click", "a.detail", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var json = "";
                	   json = json +'{"id":"'+id+ '"}';
                    $.ajax({
                    	"contentType":"application/json; charset=UTF-8",
                    	type:"post",
                        url: ctx + "/about/detail",
                        data: json,
                        dataType:"json",
                        success: function(msg){
                        	$("#detialBody").empty();// clean
                        	var tmpl = $("#detialTemplate").tmpl(msg).appendTo("#detialBody");
                        	var modal = $('#myModal2').modal('show');
                        	modal.on("hidden.bs.modal",function(e){
                        		$(this).removeData();
                        	});
                        	
                        	$("#detialConfirm").unbind("click").click(function(){
                                    modal.modal('hide');
                                });
                        	},
                        
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                    }));*/
                
                //报修
                $('#deviceEditable').on("click", "a.repair", function (e) {
                    e.preventDefault();
                    var obj = $(this);
                    bootbox.confirm("申请报修此套设备?", function(result) {
                        if (result) {
                        	var nRow = obj.parents('tr')[0];
                            var id = nRow.children[0].id;
                            $.ajax({
                            	"contentType":"application/json; charset=UTF-8",
                            	type:"post",
                                url: ctx + "/device/repair",
                                data:"{"+'"id":"'+id+'"}',
                                dataType:"json",
                                success: function(msg){
                                	if (msg.code == 1) {
                                		bootbox.alert("申请成功！");
                                		oTable.fnDraw(false);
                                	} else {
                                		bootbox.alert(msg.message);
                                	}
                                },
                                error: function (msg) {
                                	bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                });
                
                //归还设备
                $('#deviceEditable').on("click", "a.pullback", function (e) {
                    e.preventDefault();
                    var obj = $(this);
                    bootbox.confirm("回收此套设备?", function(result) {
                        if (result) {
                        	var nRow = obj.parents('tr')[0];
                            var id = nRow.children[0].id;
                            $.ajax({
                            	"contentType":"application/json; charset=UTF-8",
                            	type:"post",
                                url: ctx + "/device/pullback",
                                data:"{"+'"id":"'+id+'"}',
                                dataType:"json",
                                success: function(msg){
                                	if (msg.code == 1) {
                                		bootbox.alert("回收成功！");
                                		oTable.fnDeleteRow(nRow);
                                	} else {
                                		bootbox.alert(msg.message);
                                	}
                                },
                                error: function (msg) {
                                	bootbox.alert(msg.message);
                                }
                            });
                        }
                    });
                });
                
                //分配
                $('#deviceEditable').on("click", "a.distribution", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var orgId =nRow.children[1].id;
                    var json = '{"id":"'+id+'","orgId":"'+orgId+'"}'
                    $.ajax({
                    	"contentType":"application/json; charset=UTF-8",
                    	type:"post",
                        url: ctx + "/device/distribution",
                        data: json,
                        dataType:"json",
                        success: function(msg){
                        	$("#distributionBody").empty();// clean
                        	var tmpl = $("#distributionTemplate").tmpl(msg).appendTo("#distributionBody");
                        	var modal = $('#distributionModal').modal('show');
                        	modal.on("hidden.bs.modal",function(e){
                        		$(this).removeData();
                        	});
                        	//Autocomplete
                            $("#employeeNoSearch").autocomplete({
                                source: function(query,process){
                                	$.ajax({
                	                	"contentType":"application/json; charset=UTF-8",
                                        "dataType" : 'json',
                                        "type" : "POST",
                                        "url" : ctx + "/device/employee/"+query.term,
                                        "data" : {"matchCount":200},
                                        "success" : function(data){
                                        	var ebean = []
                                        	for (var int = 0; int < data.length; int++) {
                                        		var temp = [];
                                        		temp.label = data[int].employeeName +"  "+ data[int].employeeNo;
                                        		temp.value = data[int].employeeNo;
                                        		ebean.push(temp);
                                    		}
                                            return process(ebean);
                                        }
                	                })
//                                    $.post(ctx + "/device/employee/"+query.term,{"matchCount":200},function(data){
//                                    	var ebean = []
//                                    	for (var int = 0; int < data.length; int++) {
//                                    		var temp = [];
//                                    		temp.label = data[int].employeeName +"  "+ data[int].employeeNo;
//                                    		temp.value = data[int].employeeNo;
//                                    		ebean.push(temp);
//                                		}
//                                        return process(ebean);
//                                    });
                                },
                                search:function(event, ui){
                                	$("#employeeNo").val("");
                                },
                                select: function(event, ui) {
                                    $("#employeeNoSearch").val(ui.item.label);
                                    $("#employeeNo").val(ui.item.value);
                                    var uistr =ui.item;
                                    // 阻止事件的默认行为
                                    event.preventDefault(); 
                                }
                            });
                        	$("#distributionConfirm").unbind("click").click(function(){
                        		var json = $("form#distributionForm").serializeJSON();
      	                	  	var modal = $('#distributionModal');
                                $.ajax({
                                	  "contentType":"application/json; charset=UTF-8",
                                	  type:"post",
                                    url: ctx + "/device/doDistribution",
                                    data: json,
                                    dataType:"json",
                                    success: function(msg){
                                    	if (msg.code == 1) {
                                    		bootbox.alert("分配成功！");
                                    		oTable.fnDraw(false);
                                    		modal.modal('hide');
                                    	} else {
                                    		bootbox.alert(msg.message);
                                    	}
                                    },
                                    error: function (msg) {
                                    	bootbox.alert(msg.message);
                                    }
                                });
                                });
                        	},
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                    }));
                
                //编辑
                /*$('#deviceEditable').on("click", "a.edit", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var json = "";
                	   json = json +'{"id":"'+id+ '"}';
                    $.ajax({
                    	"contentType":"application/json; charset=UTF-8",
                    	type:"post",
                        url: ctx + "/about/detail",
                        data: json,
                        dataType:"json",
                        success: function(msg){
                        	$("#editBody").empty();// clean
                        	var tmpl = $("#editTemplate").tmpl(msg).appendTo("#editBody");
                        	var modal = $('#myModal3').modal('show');
                        	modal.on("hidden.bs.modal",function(e){
                        		$(this).removeData();
                        	});
                        	
                        	$("#editConfirm").unbind("click").click(function(){
                                    modal.modal('hide');
                                });
                        	},
                        
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                    }));*/
                //查询
                $('#queryBtn').click(function(){
                	oTable.fnClearTable();
                });
                $('#cancleQuery').click(function(){
                	//重置按钮 清空datepicker缓存
                	$('#endStart').datepicker('setDate', null);
                	$('#endEnd').datepicker('setDate', null);
                });
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();